/*
 * This file is part of shared-drawing.
 * shared-drawing is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option )
 * any later version. shared-drawing is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * You should have received a copy of the GNU General Public License along with 
 * shared-drawing. If not, see http://www.gnu.org/licenses/.
 */

package primitives;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import SharedDrawing.WgContent;
import common.XmlConstants;

public class P_Line extends Primitive 
{
	private Line2D m_line;

	public void initPrimitive(int x, int y, int width, boolean fill, Color color, Color border)
	{
		try 
		{
			m_type = this.getClass().getSimpleName();
			initPrimitive(width, fill, color, border);
			m_line = new Line2D.Float(x, y, x, y);
		} 
		catch (Exception err) 
		{
			System.out.println("Erreur d'instanciation: " + err);
		}
	}	
	
	@Override
	public boolean isOverObject(int x, int y) 
	{
		if (m_line.intersects(x - 5, y - 5, 5, 5)) 
		{
			return true;
		}
		return false;
	}
	
	@Override
	public void drawComponent(Graphics2D g) 
	{
		g.setStroke(new BasicStroke(m_width));
		
		g.setColor(m_borderColor);
		g.draw(m_line);
	}
	
	@Override
	public void setShape(int x1, int y1, int x2, int y2) 
	{
		m_line.setLine(x1, y1, x2, y2);
	}
	
	@Override
	public WgContent toWgContent()
    {
		WgContent wg = new WgContent(m_type);
		
		wg.addContent(XmlConstants.primitiveId, String.valueOf(m_elementId));
		wg.addContent(XmlConstants.primitiveX, String.valueOf((int)m_line.getX1()));
        wg.addContent(XmlConstants.primitiveY, String.valueOf((int)m_line.getY1()));
        wg.addContent(XmlConstants.primitiveX2, String.valueOf((int)m_line.getX2()));
        wg.addContent(XmlConstants.primitiveY2, String.valueOf((int)m_line.getY2()));
		wg.addContent(XmlConstants.primitiveWidth, String.valueOf(m_width));
        wg.addContent(XmlConstants.primitiveBorderColor, Integer.toHexString(m_borderColor.getRGB()));
        
        return wg;
    }
    
	@Override
	public void fromWgContent(WgContent wg)
    {
		m_width = Integer.parseInt(wg.get(XmlConstants.primitiveWidth));
        m_borderColor = Color.decode("0x" + wg.get(XmlConstants.primitiveBorderColor).substring(2));
       
        m_line.setLine(Integer.parseInt(wg.get(XmlConstants.primitiveX)),
        			   Integer.parseInt(wg.get(XmlConstants.primitiveY)),
        			   Integer.parseInt(wg.get(XmlConstants.primitiveX2)),
        			   Integer.parseInt(wg.get(XmlConstants.primitiveY2)));
    }

	@Override
	public Object getShape() {
		return m_line;
	}
}